package com.kfgj.hkp.common.components.domain;

import com.kfgj.hkp.common.components.http.HttpHelper;
import com.kfgj.hkp.common.components.xml.XmlTransformUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by liwensihan on 2015/1/15.
 *
 * @author liwensihan
 */
public class DomainNameHelper {

    private static String uri = "http://panda.www.net.cn/cgi-bin/check.cgi?area_domain=%s";

    public static DomainName checkDomain(String name) {

        if (!StringUtils.isNotEmpty(name)) {
            return null;
        }
        name = name.endsWith(".com") ? name : name + ".com";

        String url = String.format(uri, name);

        DomainName dn = new DomainName();
        dn.setName(name);
        String result = HttpHelper.getRequest(url);
        if (StringUtils.isNotEmpty(result)){
            if (result.contains("|216|")){
                throw new QueryFrequencyException("域名查询接口调用过于频繁，稍后再试!");
            }else if (!result.contains("<?xml")){
                throw new RuntimeException(String.format("调用域名查询接口出错,结果为：%s",result));
            }
            DomainDto dto = (DomainDto) XmlTransformUtil.xml2obj(result, DomainDto.class);
            if (dto != null) {
                String ori = dto.getOriginal();
                dn.setIsAvailable(ori != null && ori.contains("210") ? true : false);
            }else {
                dn.setIsAvailable(false);
            }
        }
        return dn;
    }

    public static void main(String[] args) {
        int i = 0;
        for (i = 0; i < 2; i++) {
            DomainName dn = checkDomain(i + ".com");
            if (dn.getIsAvailable()) {
                System.out.println(dn);
            }
        }
    }
}
